// SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
// SPDX-License-Identifier: Mulan PSL v2
package handler

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	chTranslations "github.com/go-playground/validator/v10/translations/zh"

	"code.geniusai.org/notebook-manager/pkg/entity"
	"code.geniusai.org/notebook-manager/pkg/log"
)

type HandlerFunc func(c *gin.Context) error

var trans ut.Translator

// 封装handler，返回的error不为nil的时候，就写入固定格式的错误结果
func Wrapper(handler HandlerFunc) func(c *gin.Context) {
	return func(c *gin.Context) {
		err := handler(c)
		if err == nil {
			return
		}
		e, ok := err.(*entity.AIPError)
		if ok {
			c.JSON(http.StatusOK, entity.HttpRespond{
				Code:    e.Code,
				Msg:     e.Msg,
				Success: false,
				Data:    nil,
			})
		} else {
			if ginErr, ok := err.(validator.ValidationErrors); ok {
				msg := ""
				for k, v := range ginErr.Translate(trans) {
					msg += fmt.Sprintf("%v: %v; ", k, v)
				}
				c.JSON(http.StatusOK, entity.HttpRespond{
					Code:    entity.CodeParamInvalid,
					Msg:     msg,
					Success: false,
					Data:    nil,
				})
				return
			}
			log.Errorf("get error(not AIPError): %v", err)
			c.JSON(http.StatusOK, entity.HttpRespond{
				Code:    entity.CodeSystemError,
				Msg:     entity.MsgSystemError,
				Success: false,
				Data:    nil,
			})
		}
		c.Abort()
	}
}

func init() {
	local := "zh"
	validate, ok := binding.Validator.Engine().(*validator.Validate)
	if !ok {
		panic("validate error")
	}
	zhT, enT := zh.New(), en.New()
	uni := ut.New(enT, zhT, enT)
	var found bool
	trans, found = uni.GetTranslator(local)
	if !found {
		panic("translator not found")
	}
	err := chTranslations.RegisterDefaultTranslations(validate, trans)
	if err != nil {
		panic(fmt.Sprintf("RegisterDefaultTranslations error: %v", err))
	}
}
